package com.sina.mysql.config;

import org.springframework.core.NamedThreadLocal;
import org.springframework.transaction.TransactionDefinition;

/**
 * @ClassName TransactionDefinitionHolder
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:20
 * @Version 1.0
 */
public abstract class TransactionDefinitionHolder {

    private static final ThreadLocal<TransactionDefinition> HOLDER = new NamedThreadLocal<>("事务定义");

    public static TransactionDefinition get() {
        return HOLDER.get();
    }

    public static void set(TransactionDefinition transactionDefinition) {
        if (transactionDefinition == null) {
            clear();
        } else {
            HOLDER.set(transactionDefinition);
        }
    }

    public static boolean isReadOnly() {
        TransactionDefinition transactionDefinition = get();
        return transactionDefinition != null && transactionDefinition.isReadOnly();
    }

    /**
     * 事务隔离级别
     *
     * @return null or level
     */
    public static Integer getLevel() {
        TransactionDefinition transactionDefinition = get();
        Integer level = null;
        if (transactionDefinition != null) {
            level = transactionDefinition.getIsolationLevel();
        }
        return level;
    }

    public static void clear() {
        HOLDER.remove();
    }


}
